package com.quanquan.store.service;

import DTO.PageDTO;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.quanquan.store.dto.ShopMallDTO;
import com.quanquan.store.entity.Coupon;
import com.quanquan.store.entity.ShopMall;
import com.quanquan.store.repository.CouponCodeRepository;
import com.quanquan.store.repository.CouponRepository;
import com.quanquan.store.repository.ShopMallRepository;
import com.quanquan.store.request.ShopMallRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import utils.DateUtils;
import utils.StringUtil;
import utils.UUIDGenerator;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * @ClassName:ShopMallService
 * @Description:TODO
 * @Author:xiongjunbao
 * @Date:2019/8/12 13:47
 * @Version 1.0
 */
@Service
public class ShopMallService {

    private final ShopMallRepository shopMallRepository;
    private final CouponRepository couponRepository;
    private final CouponCodeRepository couponCodeRepository;

    @Autowired
    public ShopMallService(ShopMallRepository shopMallRepository, CouponRepository couponRepository, CouponCodeRepository couponCodeRepository) {
        this.shopMallRepository = shopMallRepository;
        this.couponRepository = couponRepository;
        this.couponCodeRepository = couponCodeRepository;
    }

    /**
     * 保存积分商城
     *
     * @param request
     * @return
     */
    public String saveShopMall(ShopMallRequest request) {
        Date date = new Date();
        ShopMall shopMall = new ShopMall();
        BeanUtil.copyProperties(request, shopMall, true, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        shopMall.setId(UUIDGenerator.getUUID());
        //后台插件的问题，未精确到秒，这里补全，不然保存报错
        shopMall.setBuyTimeStart(DateUtils.dateToString(DateUtils.strToDate(request.getBuyTimeStart() + ":00", DateUtils.TIMESTAMP), DateUtils.TIMESTAMP));
        shopMall.setBuyTimeEnd(DateUtils.dateToString(DateUtils.strToDate(request.getBuyTimeEnd() + ":00", DateUtils.TIMESTAMP), DateUtils.TIMESTAMP));
        shopMall.setShowTimeStart(DateUtils.dateToString(DateUtils.strToDate(request.getShowTimeStart() + ":00", DateUtils.TIMESTAMP), DateUtils.TIMESTAMP));
        shopMall.setShowTimeEnd(DateUtils.dateToString(DateUtils.strToDate(request.getShowTimeEnd() + ":00", DateUtils.TIMESTAMP), DateUtils.TIMESTAMP));
        Coupon coupon = couponRepository.findByCouponId(request.getCouponId());
        //如果取到的券剩余量不足建券，商城建券失败
        if (coupon.getSumType() == 0) {
            if (coupon.getRemainTotal() < request.getSumTotal()) {
                return "该券余量不足，请调整后再行创建";
            }
            coupon.setRemainTotal(coupon.getRemainTotal() - request.getSumTotal());
            couponRepository.saveAndFlush(coupon);
        }
        shopMall.setSumTotal(request.getSumTotal());
        shopMall.setRemainTotal(request.getSumTotal());
        shopMall.setStatusRemove(0);
        shopMall.setStatusShow(1);
        shopMall.setCount(request.getCount());
        shopMall.setBuyTimeCount(request.getBuyTimeCount());
        shopMall.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
        shopMall.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
        shopMallRepository.saveAndFlush(shopMall);
        return "创建成功";
    }

    /**
     * 更新积分商城
     *
     * @param request
     * @return
     */
    public String updateShopMall(ShopMallRequest request) {
        ShopMall shopMall = shopMallRepository.findByStatusRemoveAndId(request.getId());
        if (shopMall == null) {
            return "未在商城中找到该商品";
        }
        BeanUtil.copyProperties(request, shopMall, true, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        shopMall.setBuyTimeStart(DateUtils.dateToString(DateUtils.strToDate(request.getBuyTimeStart() + ":00", DateUtils.TIMESTAMP), DateUtils.TIMESTAMP));
        shopMall.setBuyTimeEnd(DateUtils.dateToString(DateUtils.strToDate(request.getBuyTimeEnd() + ":00", DateUtils.TIMESTAMP), DateUtils.TIMESTAMP));
        shopMall.setShowTimeStart(DateUtils.dateToString(DateUtils.strToDate(request.getShowTimeStart() + ":00", DateUtils.TIMESTAMP), DateUtils.TIMESTAMP));
        shopMall.setShowTimeEnd(DateUtils.dateToString(DateUtils.strToDate(request.getShowTimeEnd() + ":00", DateUtils.TIMESTAMP), DateUtils.TIMESTAMP));
        Coupon coupon = couponRepository.findByCouponId(request.getCouponId());
        //如果取到的券剩余量不足建券，商城更新失败（考虑到其他地方有操作相同券，券量不足的问题）
        /*if (coupon.getSumType() == 0) {
            if (coupon.getRemainTotal() < shopMall.getRemainTotal()) {
                return "该券余量不足，请调整后更新";
            }
        }*/
        //库存增加量，如果传来的库存和原本库存不一致，对库存进行调整
        Integer count = request.getSumTotal() - shopMall.getSumTotal();
        shopMall.setSumTotal(request.getSumTotal());
        if (coupon.getSumType() == 0) {
            if (coupon.getRemainTotal() < count) {
                return "该券余量不足，请调整后更新";
            }
            coupon.setRemainTotal(coupon.getRemainTotal() - count);
            couponRepository.saveAndFlush(coupon);
        }
        shopMall.setRemainTotal(shopMall.getRemainTotal() + count);
        shopMall.setStatusRemove(0);
        shopMall.setStatusShow(1);
        shopMall.setCount(request.getCount());
        shopMall.setBuyTimeCount(request.getBuyTimeCount());
        shopMall.setUpdateTime(DateUtils.currentDate());
        shopMallRepository.saveAndFlush(shopMall);
        return "更新成功";
    }

    /**
     * 后台用查询商城商品列表
     *
     * @param requestBody
     * @return
     */
    public PageDTO<ShopMallDTO> queryByCondition(ShopMallRequest requestBody) {
        //分页
        Integer page = null == requestBody.getPage() ? 0 : requestBody.getPage();
        Integer size = null == requestBody.getSize() ? 10 : requestBody.getSize();
        //创建时间区间
        String fromDate = requestBody.getFromDate();
        String toDate = requestBody.getToDate();
        Integer statusShow = requestBody.getStatusShow();
        Integer statusRemove = requestBody.getStatusRemove();
        //排序状态
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        //搜索关键词
        String keyword = requestBody.getKeyword();
        Pageable pageable = PageRequest.of(page, size, sort);
        Page<ShopMall> paged = shopMallRepository.findAll((Specification<ShopMall>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            // 创建具体查询条件
            if (null != statusShow) {
                predicates.add(criteriaBuilder.equal(root.get("statusShow").as(Integer.class), statusShow));
            }
            if (null != statusRemove) {
                predicates.add(criteriaBuilder.equal(root.get("statusRemove").as(Integer.class), statusRemove));
            }
            if (StringUtil.isNotEmpty(fromDate)) {
                Date startOfDay = DateUtils.getStartOfDay(DateUtils.strToDate(fromDate, DateUtils.DATE));
                predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime").as(Date.class), startOfDay));
            }
            if (StringUtil.isNotEmpty(toDate)) {
                Date endOfDay = DateUtils.getEndOfDay(DateUtils.strToDate(toDate, DateUtils.DATE));
                predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("createTime").as(Date.class), endOfDay));
            }
            if (StringUtil.isNotEmpty(keyword)) {
                Predicate p1 = criteriaBuilder.like(root.get("name").as(String.class), "%" + keyword + "%");
                Predicate p2 = criteriaBuilder.or(criteriaBuilder.like(root.get("couponDesc").as(String.class), "%" + keyword + "%"), p1);
                Predicate p3 = criteriaBuilder.or(criteriaBuilder.like(root.get("price").as(String.class), "%" + keyword + "%"), p2);
                predicates.add(p3);
            }
            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        }, pageable);
        List<ShopMallDTO> shopMallDTOS = new LinkedList<>();
        for (ShopMall shopMall : paged.getContent()) {
            ShopMallDTO shopMallDTO = new ShopMallDTO();
            BeanUtils.copyProperties(shopMall, shopMallDTO);
            Coupon coupon = couponRepository.findByCouponId(shopMall.getCouponId());
            shopMallDTO.setCouponName(coupon.getName());
            shopMallDTOS.add(shopMallDTO);
        }
        PageDTO<ShopMallDTO> dto = new PageDTO<>();
        dto.setTotal(paged.getTotalElements());
        dto.setList(shopMallDTOS);
        dto.setPage(page);
        dto.setPageSize(size);
        dto.setKeyword(requestBody.getKeyword());
        dto.setTotalPage(paged.getTotalPages());
        dto.setFromDate(fromDate);
        dto.setToDate(toDate);
        return dto;
    }

    /**
     * 根据id查找商城明细
     * @param id
     * @return
     */
    public ShopMallDTO findById(String id) {
        ShopMallDTO shopMallDTO = new ShopMallDTO();
        ShopMall shopMall = shopMallRepository.findByStatusRemoveAndId(id);
        BeanUtils.copyProperties(shopMall, shopMallDTO);
        return shopMallDTO;
    }

    /**
     * 更新积分商城
     *
     * @param request
     * @return
     */
    public String deleteShopMall(ShopMallRequest request) {
        ShopMall shopMall = shopMallRepository.findByStatusRemoveAndId(request.getId());
        if (shopMall == null) {
            return "未在商城中找到该商品";
        }
        Coupon coupon = couponRepository.findByCouponId(request.getCouponId());
        //如果取到的券剩余量不足建券，商城更新失败（考虑到其他地方有操作相同券，券量不足的问题）
        coupon.setRemainTotal(shopMall.getRemainTotal());
        couponRepository.saveAndFlush(coupon);
        shopMall.setRemainTotal(0);
        shopMall.setStatusRemove(1);
        shopMall.setStatusShow(1);
        shopMall.setUpdateTime(DateUtils.currentDate());
        shopMallRepository.saveAndFlush(shopMall);
        return "删除成功";
    }

    /**
     * 积分商城商品上下架
     *
     * @param request
     * @return
     */
    public boolean updateStatus(ShopMallRequest request) {
        ShopMall shopMall = shopMallRepository.findByStatusRemoveAndId(request.getId());
        if (shopMall == null) {
            return false;
        }
        if (shopMall.getStatusShow()==1){
            shopMall.setStatusShow(0);
        }else{
            shopMall.setStatusShow(1);
        }
        shopMallRepository.saveAndFlush(shopMall);
        return true;
    }

    /**
     * 前端用商城商城列表查询
     *
     * @return
     */
    public List<ShopMall> findByStatusRemoveAndStatusShow() {
        return shopMallRepository.findByStatusRemoveAndStatusShow(0, 0);
    }

}
